package com.itdfq.Fu;

import java.lang.reflect.Field;

/**
 * @Author: GodChin
 * @Date: 2021/8/16 15:59
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description: 通过子类获取父类对象的属性和方法
 */
public class Test {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
       Class<Son> s =  Son.class;
        Field publicName = getDeclaredField(s.newInstance(), "publicName");
        System.out.println(publicName);
    }
    public static Field getDeclaredField(Object obj, String fieldName) {
        Field field = null;
        Class c = obj.getClass();
        for(; c != Object.class ; c = c.getSuperclass()){
            try {
                field = c.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field;
            }catch (Exception e){
                //这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
                //如果这里的异常打印或者往外抛，则就不会执行c = c.getSuperclass(),最后就不会进入到父类中了
            }
        }
        return null;
    }
    public static Object getFieldValue(Object object,String fieldName) throws Exception{
        Field field = getDeclaredField(object,fieldName);

        return field.get(object);
    }
}
